import { reactive, watch } from 'vue';
import { apiFileUploadlist } from '@/api/url/base';
import { isNullPm } from '@/utils/baseMethods';
import { Notification } from '@arco-design/web-vue';

export default function importConfigFunction(_props: any, option: any) {
  const { emit } = option;
  const base = reactive<any>({
    fileList: [],

    steamList: [],
  });

  /**
   * @function customReques
   * @description 自定义上传行为
   */
  const customReques = (_option: any, _type: any) => {
    const { fileItem } = _option;
    base.steamList.push(fileItem);
    if (base.fileList.length > 0) {
      base.fileList.map((res: any, index: any) => {
        if (isNullPm(res.url)) {
          base.fileList.splice(index, 1);
        }
      });
    } else {
      base.fileList = [];
    }
    base.steamList.map((res: any, index: any) => {
      base.fileList.push({
        name: res.name,
        url: res.url,
        uid: res.uid,
        file: res.file,
      });
    });
    const result = base.fileList.reduce(function (prev, current) {
      const exists = prev.some(function (item) {
        return item.name === current.name;
      });
      if (!exists) {
        prev.push(current);
      }
      return prev;
    }, []);
    base.fileList = result;
  };

  /**
   * @exports getUpdata 点击上传文件
   * @param param
   */
  const getUpdata = () => {
    const formData = new FormData();
    base.fileList.map((res: any) => {
      if (!isNullPm(res.file)) formData.append('files', res.file);
    });
    let sisn = 0;
    base.fileList.map((res: any) => {
      if (isNullPm(res.file)) sisn++;
    });
    formData.append('creator', 'ERP');
    // fileFileUpload(formData).then((res: any) => {
    //   if (res.code == 200) {
    //     Notification.success('上传成功');
    //     res.data.map((rea: any, index: any) => {
    //       base.fileList[index + sisn].url = import.meta.env.VITE_APP_API_BASE_IMGURL + rea;
    //       console.log(rea);
    //       base.fileList[index + sisn].filePm = rea.split('/')[3];
    //       delete rea.file;
    //     });
    //     console.log(base.fileList);
    //     emit('filelist', base.fileList);
    //   }
    // });
  };

  /**
   * @function beforeRemove
   * @description 删除图片
   * @param fileItem
   */
  const beforeRemove = (fileItem) => {
    const index = base.fileList.findIndex((item: any) => item.url == fileItem.url);
    base.fileList.splice(index, 1);
    emit('filelist', base.fileList);
  };

  watch(
    () => _props.imgList,
    () => {
      console.log(_props.imgList);
      base.fileList = [];
      if (!isNullPm(_props.imgList))
        _props.imgList.map((res: any) => {
          base.fileList.push({
            ...res,
            file: null,
          });
        });
    },
    {
      deep: true,
      immediate: true,
    },
  );

  return {
    base,
    customReques,
    beforeRemove,
    getUpdata,
  };
}
